// booking.js
const API = require('../../utils/api')
const pathUrl = require('../../utils/common.js')
Page({
  data: {
    // 场地信息
    courtId:'',
    court: {},
    // 日期相关
    calendarDays: [],
    availableDates: [],
    selectedDate: null,
    displayYear: new Date().getFullYear(),
    displayMonth: new Date().getMonth() + 1,
    formattedDate: '',
    // 时间段相关
    timeFilter: 'all', // all, morning, afternoon, evening
    timeSlots: [],
    timeHeaders: [],
    courtsList: [],
    selectedTimeSlot: null,
    selectedSlots: [],
    // 人数相关
    selectedPeople: 2,
    minPeople: 1,
    maxPeople: 6,
    
    // 时长相关
    durationOptions: [
      { hours: 1, price: 180 },
      { hours: 2, price: 360 },
      { hours: 3, price: 540 },
      { hours: 4, price: 720 }
    ],
    selectedDuration: 1,
    // 价格相关
    totalPrice: 0,
    // 预订状态
    canBook: false,
    // 预约记录相关
    bookingRecords: []
  },
  
  async onLoad(options) {
    // 如果从其他页面传入了场地ID，则加载对应场地信息
    if (options.courtId) {
      this.setData({
        courtId: options.courtId
      })
      await this.loadCourt();
    }
    // 初始化数据可用日期
    this.generateAvailableDates();
    //初始化左边时间列表
    this.generateTimeHeaders();
    // 如果有选中日期，加载预约记录并生成时间段
    if (this.data.selectedDate) {
      await this.loadBookingRecords();
    }
    this.generateTimeSlots();
    this.updateCanBookStatus();
  },
  
  // 返回上一页
  onBack: function() {
    wx.navigateBack();
  },
  
  // 加载场地信息
  async loadCourt() {
    let court = await API.courtDetails(this.data.courtId);
    court.image = pathUrl + court.image
    //加载完场地信息
    const courtsList = [];
    for(let i=1;i<=court.num;i++){
      courtsList.push({
        id:i,
        name:i+'号场'
      })
    }
    this.setData({
      court: court,
      totalPrice: court.price,
      courtsList: courtsList
    });
  },
  
  // 生成可用日期列表（未来5天）
  generateAvailableDates: function() {
    const today = new Date();
    const availableDates = [];
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    for (let i = 0; i < 5; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);
      // 格式化月份和日期，确保两位数格式
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      availableDates.push({
        id: date.getTime(),
        date: date,
        dayOfWeek: weekDays[date.getDay()],
        day: date.getDate(),
        month: date.getMonth() + 1,
        year: date.getFullYear(),
        formatted: `${date.getFullYear()}-${month}-${day}`
      });
    }
    this.setData({
      availableDates: availableDates,
      selectedDate: availableDates[0], // 默认选择今天,
      formattedDate:availableDates[0].formatted ////默认初始化第一天
    });
  },
  
  // 生成时间段头部信息
  generateTimeHeaders: function() {
    const timeHeaders = [];
    // 生成9:00到22:00的时间段
    for (let hour = 9; hour <= 22; hour++) {
      // 格式化小时为两位数
      const formattedHour = String(hour).padStart(2, '0');
      timeHeaders.push({
        id: hour.toString(),
        time: `${formattedHour}:00`
      });
    }
    this.setData({
      timeHeaders: timeHeaders
    });
  },
  
  // 更新可预订状态
  updateCanBookStatus: function() {
    const canBook = this.data.selectedDate !== null && this.data.timeSlots.length > 0;
    this.setData({
      canBook: canBook
    });
  },
  
  // 加载预约记录 - 确保每次选择日期都重新查询数据
  async loadBookingRecords() {
      if (!this.data.selectedDate || !this.data.court.id) {
        return;
      }
      // 显示加载中提示
      wx.showLoading({
        title: '加载中...',
      });
      try{
        let queryForm = {id:this.data.courtId,date:this.data.formattedDate};
        let res = await API.bookedRecords(queryForm)
        this.setData({
          bookingRecords: res
        });
        wx.hideLoading();
      }catch(error){
        wx.showToast({
          title: '加载预约记录失败',
          icon: 'none'
        });
        wx.hideLoading();
      }
  },
  // 生成时间段数据
  generateTimeSlots: function() {
    const timeSlots = [];
    const courtsList = this.data.courtsList;
    const today = new Date();
    const currentHour = today.getHours();
    let price = this.data.court.price; // 默认价格
    // 为每个场地生成时间段
    courtsList.forEach(court => {
      // 生成9:00到22:00的时间段
      for (let hour = 9; hour <= 22; hour++) {
        let status = 'available';
        let checked = false;
        let timeType = '';
        // 检查是否已被预约
        const slotId = `${court.id}-${hour}`;
        // 格式化小时为两位数
        const formattedHour = String(hour).padStart(2, '0');
        const formattedNextHour = String(hour + 1).padStart(2, '0');
        let tempTime = `${formattedHour}:00` + '-' +(hour+1)+':00';
        const bookedData = this.data.bookingRecords.find(record => record.bookingDate == this.data.formattedDate &&record.bookingTime ==tempTime&&record.num ==court.id);
        if(bookedData){
          status = 'disabled';
          //checked = true;
        }
        timeSlots.push({
          id: slotId,
          courtId: court.id,
          courtName: court.name,
          time: hour.toString(),
          timeText: `${formattedHour}:00`,
          nextHour: hour + 1,
          formattedNextHour: formattedNextHour,
          status: status,
          price: price,
          timeType: timeType,
          num:court.id,
          endTime:tempTime,
          checked: checked
        });
      }
    });
    
    this.setData({
      timeSlots: timeSlots
    });
  },
  
  // 获取特定场地和时间段的可用时段
  getCourtTimeSlots: function(timeId, courtId) {
    return this.data.timeSlots.filter(slot => slot.time === timeId && slot.courtId === court.id);
  },
  
  // 格式化日期为字符串
  formatDate: function(date) {
    if (!date) return '';
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${year}年${month}月${day}日`;
  },
  
  // 判断时段是否被选中
  isSlotSelected: function(slotId) {
    return this.data.selectedSlots.some(s => s.id === slotId);
  },
  
  // 选择日期
  async selectDate(e) {
    const index = e.currentTarget.dataset.index;
    const selectedDate = this.data.availableDates[index];
    this.setData({
      selectedDate: selectedDate,
      formattedDate: selectedDate.formatted
    });
    // 加载所选日期的预约记录
    await this.loadBookingRecords();
    // 重新生成时间段数据
    this.generateTimeSlots();
    // 重置选中的场次
    this.setData({
      selectedSlots: [],
      totalPrice: 0
    });
    this.loadCourt();
  },
  
  // 选择时间段 - 改为多选模式
  selectTimeSlot: function(e) {
    const slotId = e.currentTarget.dataset.id;
    const timeSlots= this.data.timeSlots;
    const slot = timeSlots.find(s => s.id === slotId);
    // 如果时段不可用，显示提示
    if (slot.status !== 'available') {
      if (slot.status === 'booked') {
        wx.showToast({
          title: '该时段已被预订',
          icon: 'none',
          duration: 1500
        });
      } else if (slot.status === 'disabled') {
        wx.showToast({
          title: '该时段不可预订',
          icon: 'none',
          duration: 1500
        });
      }
      return;
    }
    // 检查该时段是否已被选中
    const isSelected = this.data.selectedSlots.some(s => s.id === slotId);
    let selectedSlots = [...this.data.selectedSlots];
    let totalPrice = this.data.totalPrice;
    
    if (isSelected) {
      // 如果已选中，则移除
      const index = selectedSlots.findIndex(s => s.id === slotId);
      totalPrice -= selectedSlots[index].price;
      selectedSlots.splice(index, 1);
      slot.checked = false;
    } else {
      // 如果未选中，则添加
      selectedSlots.push(slot);
      totalPrice += slot.price;
      slot.checked = true;
    }
    let totalPrices = this.data.court.price*selectedSlots.length;
    this.setData({
      selectedSlots: selectedSlots,
      totalPrice: totalPrices,
      timeSlots:timeSlots
    });
  },
  
  // 移除已选场次
  removeSelectedSlot: function(e) {
    const slotId = e.currentTarget.dataset.id;
    let selectedSlots = [...this.data.selectedSlots];
    let totalPrice = this.data.totalPrice;
    // 找到并移除选中的场次
    const index = selectedSlots.findIndex(s => s.id === slotId);
    if (index > -1) {
      totalPrice -= selectedSlots[index].price;
      selectedSlots.splice(index, 1);
      this.setData({
        selectedSlots: selectedSlots,
        totalPrice: totalPrice
      });
    }
  },
  
  // 提交预订
   submitBooking() {
    if (this.data.selectedSlots.length === 0) {
      wx.showToast({
        title: '请选择至少一个时段',
        icon: 'none'
      });
      return;
    }
    let arrForm = [];
    for(let i=0;i<this.data.selectedSlots.length;i++){
      let slot = this.data.selectedSlots[i];
      let submitForm = {
        placeId: this.data.court.id,
        placeName: this.data.court.name,
        bookingDate: this.data.selectedDate.formatted,
        bookingTime: slot.endTime,
        price: slot.price,
        num: slot.num 
      };
      arrForm.push(submitForm);
    }
    // 显示加载提示
    wx.showLoading({
      title: '提交中...',
    });
    API.bookingPlace(arrForm).then(res=>{
      wx.hideLoading();
      wx.showToast({
        title: `成功预订${this.data.selectedSlots.length}个时段`,
        icon: 'success'
      });
      wx.navigateTo({
        url: '/pages/courts-booking-list/courts-booking-list',
      })
    }).catch(err=>{
      wx.hideLoading();
      wx.showToast({
        title: '预订失败，请重试',
        icon: 'none'
      });
    })
  }
});